package com.wangzaiplus.test.mq.listener;

import com.rabbitmq.client.Channel;
import com.wangzaiplus.test.common.Constant;
import com.wangzaiplus.test.config.RabbitConfig;
import com.wangzaiplus.test.mq.BaseConsumer;
import com.wangzaiplus.test.mq.BaseConsumerProxy;
import com.wangzaiplus.test.mq.MessageHelper;
import com.wangzaiplus.test.mq.consumer.LoginLogConsumer;
import com.wangzaiplus.test.pojo.LoginLog;
import com.wangzaiplus.test.service.LoginLogService;
import com.wangzaiplus.test.service.MsgLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;
@Slf4j
@Component
public class LoginLogListener {

    @Autowired
    private LoginLogConsumer loginLogConsumer;

    @Autowired
    private MsgLogService msgLogService;
    @Autowired
    private LoginLogService loginLogService;

     @RabbitListener(queues = RabbitConfig.LOGIN_LOG_QUEUE_NAME)
    public void consume(Message message, Channel channel) throws IOException {
         BaseConsumerProxy baseConsumerProxy = new BaseConsumerProxy(loginLogConsumer, msgLogService);
         BaseConsumer proxy = (BaseConsumer) baseConsumerProxy.getProxy();
         if (null != proxy) {
             proxy.consume(message, channel);
         }
     }


    /**
     * 监听消费邮件发送
     * @param message
     */
    @RabbitListener(queues = RabbitConfig.LOGIN_LOG_QUEUE_NAME)
    public void consumeMailQueue(Message message, Channel channel){
        try {
            log.info("收到消息: {}", message.toString());
            LoginLog loginLog = MessageHelper.msgToObj(message, LoginLog.class);
            if(loginLog!=null){
                loginLogService.insert(loginLog);
            }

            msgLogService.updateStatus(loginLog.getMsgId(), Constant.MsgLogStatus.CONSUMED_SUCCESS);

        }catch (Exception e){
            e.printStackTrace();
        }
    }


}
